<?php

namespace App\Console\Commands;

use App\Http\Controllers\Resource\QqrdController;
use App\Models\ResourceBusinessName;
use App\Models\ResourceQqrd;
use App\Models\ResourceTypeExternal;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class QqrdMysqlData extends Command
{

    // 使用 命令行执行  php artisan command:QqrdMysqlData
    // 若使用 linux 后台执行则使用  nohup php artisan command:QqrdMysqlData &   //输入完后，关闭命令行


    // protected $limit = 100; //每页限制条数
    protected $up_start_page = 1; //同步资源开始页，默认为 1
    protected $down_start_page = 1; //下载开始页，默认为 1
    protected $resource_business_id = 2; //资源商id

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:QqrdMysqlData';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步QQ阅读数据到数据库';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        //删除所有数据，根据需求进行处理
        // ResourceQqrd::where('is_del', 1)->update(['is_del' => 2, 'change_time' => date('Y-m-d H:i:s')]);
        // ResourceTotal::where('is_del', 1)->where('resource_business_id', $this->resource_business_id)->update(['is_del' => 2, 'change_time' => date('Y-m-d H:i:s')]);

        $resourceBusinessNameModel = new  ResourceBusinessName();
        $resource_business_name_info = $resourceBusinessNameModel->where('id', $this->resource_business_id)->where('is_del', 1)->first();
        if (empty($resource_business_name_info)) {
            Log::channel('qqrdcmdlog')->debug('资源商不存在或已被删除');
            die;
        }
        try {
            //先同步类型
            $obj = new QqrdController();
            $resourceModel = new ResourceQqrd();
            $resourceTypeExternalModel = new ResourceTypeExternal();
            $data_type = $obj->getBookType();
            if ($data_type) {
                $result_id = '';
                foreach ($data_type['data'] as $key => $val) {
                    $val['parent_id'] = $val['parentid'];
                    $val['level'] = $val['level'];
                    $val['original_id'] = $val['id'];
                    $val['resource_business_id'] = $this->resource_business_id;
                    $val['big_type_id'] = 1;
                    $result = $resourceTypeExternalModel->getTypeNameNoAdd($val);

                    $result_id .= $result . '、';
                }
                trim($result_id, '、');
                Log::channel('qqrdcmdlog')->debug('QQ阅读数据类型同步完成: ' . $result_id);
            }

            //数据太多，可能为导致更新到一半断掉
            $request_page = $resource_business_name_info['request_page'];
            if (!empty($request_page)) {
                $this->up_start_page = $request_page; //更新上架页数
            }
            //获取数据上架列表
            $up_data = $obj->qqrdUpBookList(1); //获取总数据量
            if ($up_data) {
                $total_page = $up_data['data']['maxPage'] + 1;

                Log::channel('qqrdcmdlog')->debug('全量同步上架数据开始，共 ' . $total_page . ' 页');

                //总页数+1，才会走else
                for ($i = $this->up_start_page; $i <= $total_page; $i++) {
                    if ($i % 5 == 0) {
                        sleep(1);
                    }
                    $data = $obj->qqrdUpBookList($i);
                    if ($data) {
                        $result_id = '';
                        foreach ($data['data']['cbids'] as $key => $val) {
                            //获取数据详情
                            $up_data_info = $obj->getBookDetail($val);
                            if ($up_data_info) {
                                $result = $resourceModel->addData($up_data_info['data']);
                                $result_id .= $result . '、';
                            }
                        }
                        $resourceBusinessNameModel->where('id', $this->resource_business_id)->update(['request_page' => $i + 1]); //更新页数

                        Log::channel('qqrdcmdlog')->debug('全量同步上架数据，第 ' . $i . ' 页数据处理完毕: ' . $result_id);
                    } else {
                        //同步到最后一页才重置
                        if ($i == $total_page) {
                            $resourceBusinessNameModel->where('id', $this->resource_business_id)->update(['request_page' => 1, 'request_time' => date('Y-m-d H:i:s')]); //重置页数
                        }

                        //数据太大才判断，数据量小不判断
                        if ($i == $total_page) {
                            Log::channel('qqrdcmdlog')->debug('全量同步上架数据处理完毕: 页数: ' . $i);
                        } else {
                            Log::channel('qqrdcmdlog')->debug('全量同步上架数据出现异常: 页数: ' . $i);
                            return '同步上架数据错误 error';
                        }
                    }
                }
            }

            //获取数据下架列表
            $down_data = $obj->qqrdDownBookList(1);
            if ($down_data) {
                //直接删除数据
                for ($i = $this->down_start_page; $i <= $down_data['data']['maxPage']; $i++) {
                    $data = $obj->qqrdDownBookList($i);
                    if ($data) {
                        $result_id = '';
                        foreach ($data['data']['cbids'] as $key => $val) {
                            $resourceModel->deleteData($val);
                            $result_id .= $val . '、';
                        }
                        Log::channel('qqrdcmdlog')->debug('全量同步下架数据，第 ' . $i . ' 页数据处理完毕: ' . $result_id);
                    } else {
                        Log::channel('qqrdcmdlog')->debug('全量同步下架数据处理完毕: 页数: ' . $i);
                        break;
                    }
                }
            }
            Log::channel('qqrdcmdlog')->debug('数据全部同步完成');
            // echo '数据全部同步完成';
            //更新同步时间
            $resourceBusinessNameModel->where('id', $this->resource_business_id)->update(['last_synch_time' => date('Y-m-d H:i:s')]);
        } catch (\Exception $e) {
            Log::channel('qqrdcmdlog')->debug('数据处理出现异常:' . $e->getMessage() . ';File:' . $e->getFile() . ';Line:' . $e->getLine() . ';');
        }
    }
}
